# -*- coding: UTF-8 -*-
from django import forms
from django.contrib.auth.models import User, Group
from django.utils.translation import gettext as _

class SignupForm(forms.Form):
    username = forms.CharField(max_length=40, widget=forms.widgets.TextInput(\
        attrs={'style':'width: 10em;'}), label='登录名')
    shopname = forms.CharField(max_length=40, widget=forms.widgets.TextInput(\
        attrs={'style':'width: 10em;'}), label='登录名')
    password = forms.CharField(max_length=40,\
        widget=forms.widgets.PasswordInput(attrs={'style':'width: 10em;'}),\
        label='密码')
    rpassword = forms.CharField(max_length=40,\
        widget=forms.widgets.PasswordInput(attrs={'style':'width: 10em;'}),\
        label='确认密码')

    def clean_username(self):
        n = self.cleaned_data['username']
        try:
            User.objects.get(username=n)
        except User.DoesNotExist:
            return n
        raise forms.ValidationError(_('用户名 "%s" 已存在') % n)

    def clean_rpassword(self):
        p = self.cleaned_data['password']
        rp = self.cleaned_data['rpassword']
        if p==rp:
            return p
        raise forms.ValidationError(_('两次输入的密码不一致'))

    def save(self):
        user_obj = User.objects.create_user(\
            username=self.cleaned_data['username'], email='',\
            password=self.cleaned_data['password'])
        user_obj.is_staff = True
        user_obj.is_superuser = False
        user_obj.first_name = self.cleaned_data['shopname']
        user_obj.save()
        #普通用户分组
        business_users = Group.objects.get_or_create(name='business_users')
        user_obj.groups.add(business_users[0].id)
        from django.contrib.auth import authenticate
        return authenticate(username=self.cleaned_data['username'],\
                            password=self.cleaned_data['password']) 

